<template>
    <div class="promotion-management-page">
        <!-- 頁面標題 -->
        <page-title :title="'轉正管理'" />

        <!-- Tab 切換 -->
        <div class="tab-section">
            <el-tabs v-model="activeTab" @tab-click="handleTabChange">
                <el-tab-pane label="待轉正" name="pending"></el-tab-pane>
                <el-tab-pane label="已轉正" name="completed"></el-tab-pane>
            </el-tabs>
        </div>

        <!-- 篩選條件區域 -->
        <div class="filter-section">
            <el-form :model="filterForm" label-width="100px" label-position="right">
                <el-row :gutter="20">
                    <el-col :span="4">
                        <el-form-item label="入職部門">
                            <el-select v-model="filterForm.department" placeholder="請選擇部門" clearable>
                                <el-option v-for="item in departmentOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="入職職位">
                            <el-select v-model="filterForm.position" placeholder="請選擇職位" clearable>
                                <el-option v-for="item in positionOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4">
                        <el-form-item label="員工類型">
                            <el-select v-model="filterForm.employeeType" placeholder="請選擇類型" clearable>
                                <el-option v-for="item in employeeTypeOptions" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="入職日期">
                            <el-date-picker v-model="filterForm.onboardingDateRange" type="daterange"
                                range-separator="至" start-placeholder="開始日期" end-placeholder="結束日期"
                                value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="轉正日期">
                            <el-date-picker v-model="filterForm.promotionDateRange" type="daterange" range-separator="至"
                                start-placeholder="開始日期" end-placeholder="結束日期" value-format="YYYY-MM-DD" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="8">
                        <el-form-item label="關鍵字搜索">
                            <el-input v-model="filterForm.keyword" placeholder="請輸入員工姓名/手機號碼/編號" clearable
                                @clear="handleSearch" @keyup.enter="handleSearch">
                                <template #append>
                                    <el-button type="primary" @click="handleSearch">
                                        <el-icon>
                                            <Search />
                                        </el-icon>
                                    </el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>

        <!-- 操作按鈕區域 -->
        <div class="action-section">
            <template v-if="activeTab === 'pending'">
                <el-button type="warning" @click="exportEmployees">
                    <el-icon>
                        <Download />
                    </el-icon>
                    <span>導出</span>
                </el-button>
                <el-button type="info" @click="showMoreActions">
                    <el-icon>
                        <More />
                    </el-icon>
                    <span>更多操作</span>
                </el-button>
            </template>

            <template v-else-if="activeTab === 'completed'">
                <el-button type="warning" @click="exportEmployees">
                    <el-icon>
                        <Download />
                    </el-icon>
                    <span>導出</span>
                </el-button>
            </template>
        </div>

        <!-- 表格區域 -->
        <div class="table-section">
            <!-- 待轉正表格 -->
            <el-table v-if="activeTab === 'pending'" :data="pendingList" style="width: 100%" v-loading="loading"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="員工編號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="phone" label="手機號碼" width="150" />
                <el-table-column prop="onboardingDate" label="入職日期" width="150" />
                <el-table-column prop="probationPeriod" label="試用期" width="120">
                    <template #default="{ row }">
                        {{ row.probationPeriod }}個月
                    </template>
                </el-table-column>
                <el-table-column prop="expectedPromotionDate" label="轉正日期" width="150" />
                <el-table-column prop="approvalStatus" label="審批狀態" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getApprovalTagType(row.approvalStatus)">
                            {{ row.approvalStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="220" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" size="small" @click="initiatePromotionApproval(row)"
                            v-if="row.approvalStatus === '未發起'">
                            發起轉正審批
                        </el-button>
                        <el-button type="success" size="small" @click="manualPromotion(row)">
                            手動辦理轉正
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 已轉正表格 -->
            <el-table v-else-if="activeTab === 'completed'" :data="completedList" style="width: 100%"
                v-loading="loading" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="name" label="員工姓名" width="120" />
                <el-table-column prop="employeeId" label="員工編號" width="120" />
                <el-table-column prop="department" label="部門" width="150" />
                <el-table-column prop="position" label="職位" width="150" />
                <el-table-column prop="phone" label="手機號碼" width="150" />
                <el-table-column prop="onboardingDate" label="入職日期" width="150" />
                <el-table-column prop="probationPeriod" label="試用期" width="120">
                    <template #default="{ row }">
                        {{ row.probationPeriod }}個月
                    </template>
                </el-table-column>
                <el-table-column prop="expectedPromotionDate" label="原定轉正日期" width="150" />
                <el-table-column prop="actualPromotionDate" label="實際轉正日期" width="150" />
                <el-table-column prop="approvalStatus" label="審批狀態" width="120">
                    <template #default="{ row }">
                        <el-tag :type="getApprovalTagType(row.approvalStatus)">
                            {{ row.approvalStatus }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                    <template #default="{ row }">
                        <el-button type="danger" size="small" @click="cancelPromotion(row)">
                            取消轉正
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>

            <!-- 分頁 -->
            <div class="pagination-section">
                <el-pagination v-model:current-page="pagination.currentPage" v-model:page-size="pagination.pageSize"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
                    :total="pagination.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
            </div>
        </div>

        <!-- 更多操作下拉菜單 -->
        <el-dropdown ref="moreActionsDropdown" trigger="click" :hide-on-click="false">
            <div style="display: none;"></div>
            <template #dropdown>
                <el-dropdown-menu>
                    <el-dropdown-item @click="batchInitiatePromotionApproval">批量發起轉正審批</el-dropdown-item>
                    <el-dropdown-item @click="batchManualPromotion">批量手動辦理轉正</el-dropdown-item>
                </el-dropdown-menu>
            </template>
        </el-dropdown>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { Search, Download, More } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Tab 切換
const activeTab = ref('pending')

// 篩選表單
const filterForm = reactive({
    department: '',
    position: '',
    employeeType: '',
    onboardingDateRange: [],
    promotionDateRange: [],
    keyword: ''
})

// 下拉選項
const departmentOptions = [
    { value: 'rd', label: '研發部' },
    { value: 'hr', label: '人事部' },
    { value: 'finance', label: '財務部' },
    { value: 'marketing', label: '市場部' },
    { value: 'sales', label: '銷售部' }
]

const positionOptions = [
    { value: 'frontend', label: '前端開發' },
    { value: 'backend', label: '後端開發' },
    { value: 'designer', label: '設計師' },
    { value: 'product', label: '產品經理' },
    { value: 'hr', label: '人事專員' }
]

const employeeTypeOptions = [
    { value: 'fulltime', label: '全職' },
    { value: 'parttime', label: '兼職' },
    { value: 'intern', label: '實習生' },
    { value: 'contract', label: '合同工' }
]

// 表格數據
const loading = ref(false)
const pendingList = ref([
    {
        id: 1,
        name: '張三',
        employeeId: '10001',
        department: '研發部',
        position: '前端開發',
        phone: '13800138001',
        onboardingDate: '2023-03-15',
        probationPeriod: 3,
        expectedPromotionDate: '2023-06-15',
        approvalStatus: '未發起'
    },
    {
        id: 2,
        name: '李四',
        employeeId: '10002',
        department: '人事部',
        position: '人事專員',
        phone: '13800138002',
        onboardingDate: '2023-03-20',
        probationPeriod: 3,
        expectedPromotionDate: '2023-06-20',
        approvalStatus: '審核中'
    },
    {
        id: 3,
        name: '王五',
        employeeId: '10003',
        department: '市場部',
        position: '市場專員',
        phone: '13800138003',
        onboardingDate: '2023-04-10',
        probationPeriod: 6,
        expectedPromotionDate: '2023-10-10',
        approvalStatus: '已通過'
    }
])

const completedList = ref([
    {
        id: 4,
        name: '趙六',
        employeeId: '10004',
        department: '研發部',
        position: '後端開發',
        phone: '13800138004',
        onboardingDate: '2023-01-05',
        probationPeriod: 3,
        expectedPromotionDate: '2023-04-05',
        actualPromotionDate: '2023-04-10',
        approvalStatus: '已通過'
    },
    {
        id: 5,
        name: '錢七',
        employeeId: '10005',
        department: '財務部',
        position: '會計',
        phone: '13800138005',
        onboardingDate: '2022-12-01',
        probationPeriod: 3,
        expectedPromotionDate: '2023-03-01',
        actualPromotionDate: '2023-03-01',
        approvalStatus: '已通過'
    }
])

// 分頁
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 10
})

// 多選
const selectedRecords = ref([])

// 更多操作下拉菜單
const moreActionsDropdown = ref(null)

// 方法
const handleTabChange = () => {
    selectedRecords.value = []
    handleSearch()
}

const handleSearch = () => {
    loading.value = true
    // 模擬API請求
    setTimeout(() => {
        loading.value = false
    }, 500)
}

const exportEmployees = () => {
    ElMessage.info('導出功能待實現')
}

const showMoreActions = () => {
    moreActionsDropdown.value.handleClick()
}

const initiatePromotionApproval = (record) => {
    ElMessageBox.confirm(
        '確定要發起轉正審批嗎？',
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        record.approvalStatus = '審核中'
        ElMessage.success('已成功發起轉正審批')
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const manualPromotion = (record) => {
    ElMessageBox.prompt('請輸入實際轉正日期', '手動辦理轉正', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        inputValue: record.expectedPromotionDate,
        inputType: 'date',
        inputValidator: (value) => {
            if (!value) {
                return '請輸入轉正日期'
            }
            return true
        }
    }).then(({ value }) => {
        // 從待轉正列表移除
        pendingList.value = pendingList.value.filter(item => item.id !== record.id)

        // 添加到已轉正列表
        const promotedEmployee = {
            ...record,
            actualPromotionDate: value,
            approvalStatus: '已通過'
        }
        completedList.value.unshift(promotedEmployee)

        ElMessage.success('手動辦理轉正成功')
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const cancelPromotion = (record) => {
    ElMessageBox.confirm(
        '確定要取消該員工的轉正狀態嗎？',
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        // 從已轉正列表移除
        completedList.value = completedList.value.filter(item => item.id !== record.id)

        // 添加回待轉正列表
        const demotedEmployee = {
            ...record,
            actualPromotionDate: '',
            approvalStatus: '未發起'
        }
        pendingList.value.unshift(demotedEmployee)

        ElMessage.success('已取消轉正狀態')
    }).catch(() => {
        ElMessage.info('已取消操作')
    })
}

const batchInitiatePromotionApproval = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    ElMessageBox.confirm(
        `確定要批量發起 ${selectedRecords.value.length} 條轉正審批嗎？`,
        '提示',
        {
            confirmButtonText: '確定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        const ids = selectedRecords.value.map(item => item.id)
        pendingList.value.forEach(item => {
            if (ids.includes(item.id) && item.approvalStatus === '未發起') {
                item.approvalStatus = '審核中'
            }
        })
        ElMessage.success('批量發起轉正審批成功')
    }).catch(() => {
        ElMessage.info('已取消批量操作')
    })
}

const batchManualPromotion = () => {
    if (selectedRecords.value.length === 0) {
        ElMessage.warning('請至少選擇一條記錄')
        return
    }

    ElMessageBox.prompt('請輸入實際轉正日期', '批量手動辦理轉正', {
        confirmButtonText: '確定',
        cancelButtonText: '取消',
        inputType: 'date',
        inputValidator: (value) => {
            if (!value) {
                return '請輸入轉正日期'
            }
            return true
        }
    }).then(({ value }) => {
        const ids = selectedRecords.value.map(item => item.id)
        const toBeMoved = pendingList.value.filter(item => ids.includes(item.id))

        // 添加到已轉正列表
        toBeMoved.forEach(record => {
            const promotedEmployee = {
                ...record,
                actualPromotionDate: value,
                approvalStatus: '已通過'
            }
            completedList.value.unshift(promotedEmployee)
        })

        // 從待轉正列表移除
        pendingList.value = pendingList.value.filter(item => !ids.includes(item.id))

        ElMessage.success(`已成功批量辦理 ${toBeMoved.length} 條轉正記錄`)
        selectedRecords.value = []
    }).catch(() => {
        ElMessage.info('已取消批量操作')
    })
}

const handleSelectionChange = (selection) => {
    selectedRecords.value = selection
}

const handleSizeChange = (val) => {
    pagination.pageSize = val
    handleSearch()
}

const handleCurrentChange = (val) => {
    pagination.currentPage = val
    handleSearch()
}

const getApprovalTagType = (status) => {
    switch (status) {
        case '已通過': return 'success'
        case '審核中': return 'warning'
        case '未通過': return 'danger'
        default: return 'info'
    }
}
</script>

<style lang="less" scoped>
.promotion-management-page {
    padding: 20px;
    background-color: #fff;

    .tab-section {
        margin-bottom: 16px;

        :deep(.el-tabs__header) {
            margin-bottom: 0;
        }
    }

    .filter-section {
        padding: 16px;
        margin-bottom: 16px;
        background-color: #fff;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
    }

    .action-section {
        margin-bottom: 16px;
        display: flex;
        gap: 12px;
    }

    .table-section {
        background-color: #fff;
        padding: 16px;
        border-radius: 4px;
        box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);

        .pagination-section {
            margin-top: 16px;
            display: flex;
            justify-content: flex-end;
        }
    }
}
</style>